//
//  SettingViewController.m
//  SleepCare500
//
//  Created by bchy on 2019/7/31.
//  Copyright © 2019 BoChuang. All rights reserved.
//

#import "SettingViewController.h"
#import "FeedBackViewController.h"
#import "ChangePwdViewController.h"
#import <StoreKit/StoreKit.h>
#import "JPUSHService.h"
#import "SDImageCache.h"

@interface SettingViewController ()
{
    NSString *sizeStr;
}

@end

@implementation SettingViewController

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [self.tableView reloadData];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"设置";

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(wxLogined:) name:@"wxLogin" object:nil];
    
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 55;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
        cell.textLabel.textColor = BLACKTEXTCOLOR;
        cell.textLabel.font = [UIFont systemFontOfSize:15];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        cell.detailTextLabel.textColor = GRAYTEXTCOLOR;
        cell.detailTextLabel.font = [UIFont systemFontOfSize:15];
        cell.backgroundColor = [UIColor whiteColor];
    }
    

    if (indexPath.row == 0) {
        cell.textLabel.text = @"清理缓存";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.row == 1) {
        cell.textLabel.text = @"给APP评分";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }

    if (indexPath.row == 2) {
        cell.textLabel.text = @"退出登录";
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    if (indexPath.row == 0) {
        //清理缓存
        NSUserDefaults *defaultSetting = [NSUserDefaults standardUserDefaults];
        [defaultSetting setValue:@"" forKey:@"readingCache"];
        
        [[SDImageCache sharedImageCache] clearMemory];
        [[SDImageCache sharedImageCache] clearDiskOnCompletion:^{
            sizeStr = @"0B";
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.tableView reloadData];

            });
        }];
        
    }
    if (indexPath.row == 1) {
        NSString *reviewURL = @"itms-apps://itunes.apple.com/app/id1530756161";
        NSURL *url = [NSURL URLWithString:reviewURL];
        UIApplication *application = [UIApplication sharedApplication];
        if ([application respondsToSelector:@selector(openURL:options:completionHandler:)]) {
            [application openURL:url options:@{} completionHandler:^(BOOL success) {
                
            }];
        } else {
            [application openURL:url];
        }
    }
    if (indexPath.row == 2) {
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"确认退出登录吗？" message:@"登录后本地信息将会被清空" preferredStyle:UIAlertControllerStyleAlert];
           UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
           UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"退出" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
               
               User *user = [User sharedUser];
               user.userId = @"";
               user.avatar = @"";
               user.nickname = @"";
               WZLSERIALIZE_ARCHIVE(user, @"User", userFilePath);
               
               [self.navigationController popToRootViewControllerAnimated:YES];
               dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                   CYLTabBarController *tab = [UIApplication sharedApplication].keyWindow.rootViewController;
                   [tab setSelectedIndex:0];
                   LoginViewController *vc = [LoginViewController  new];
                   BaseNavigationController *nav = [[BaseNavigationController alloc] initWithRootViewController:vc];
                   nav.modalPresentationStyle = UIModalPresentationOverFullScreen;
                   [tab presentViewController:nav animated:YES completion:nil];
               });
        
               [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
                   NSLog(@"%ld, %@", iResCode, iAlias);
               } seq:1];
               
           }];
           [alert addAction:cancelAction];
           [alert addAction:confirmAction];
           [self presentViewController:alert animated:YES completion:nil];
    }
    
}

-(void)calcuateCacheSize{
    unsigned long long size = [SDImageCache sharedImageCache].totalDiskSize; //CustomFile + SDWebImage 缓存 //设置文件大小格式
    if (size >= pow(10, 9)) {
        sizeStr = [NSString stringWithFormat:@"%.2fGB", size / pow(10, 9)];
    }else if (size >= pow(10, 6)) {
        sizeStr = [NSString stringWithFormat:@"%.2fMB", size / pow(10, 6)];
    }else if (size >= pow(10, 3)) {
        sizeStr = [NSString stringWithFormat:@"%.2fKB", size / pow(10, 3)];
    }else {
        sizeStr = [NSString stringWithFormat:@"%zdB", size];
    }
    
}



-(void)wxLogined:(NSNotification *)notification{
    NSDictionary * infoDic = [notification object];
    NSLog(@"%@", infoDic);
    NSString *openid = infoDic[@"openid"];
    [self setOpenId:openid];
    
}

-(void)setOpenId:(NSString *)openId{
    [MBProgressHUD showMessag:@"" toView:self.view];
    NSDictionary *dict = @{
      @"openID": openId,
      @"userId": [User sharedUser].userId
    };
//    [NetWork sendPostUrl:@"bindWeChat" withParams:dict success:^(id responseBody) {
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//        User *user = [User sharedUser];
//        user.openId = openId;
//        WZLSERIALIZE_ARCHIVE(user, @"User", userFilePath);
//        [self.tableView reloadData];
//    } failure:^(NSError *error) {
//        [MBProgressHUD hideHUDForView:self.view animated:YES];
//    }];
}
-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
